import Vue from 'vue'
import VueRouter from 'vue-router'
import Layout from '@/layout/index'
import Handpick from '@/views/Handpick/views/Handpick.vue'
import Classification from '@/views/Classification/views/Classification.vue'
import CategoryItem from '@/views/Classification/views/CategoryItem.vue'
import Detail from '@/views/Classification/views/Detail.vue'
import ShoppingTrolley from '@/views/ShoppingTrolley/views/ShoppingTrolley.vue'
import Mine from '@/views/Mine/views/Mine.vue'
import Login from '@/views/Login/views/Login.vue'
import Register from '@/views/Login/views/Register.vue'
import GetPhoneCode from '@/views/Login/views/GetPhoneCode.vue'
import Search from '@/views/Search/views/Search.vue'

Vue.use(VueRouter)

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}

const routes = [
  {
    path: '/',
    name: 'Layout',
    component: Layout,
    redirect: 'Handpick',
    children: [
      {
        path: 'handpick',
        name: 'Handpick',
        meta: { isAuth: false, title: '精选' },
        component: Handpick
      },
      {
        path: 'classification',
        name: 'Classification',
        meta: { isAuth: false, title: '分类' },
        component: Classification
      },
      {
        path: 'shoppingtrolley',
        name: 'ShoppingTrolley',
        meta: { isAuth: true, title: '购物车' },
        component: ShoppingTrolley
      },
      {
        path: 'mine',
        name: 'Mine',
        meta: { isAuth: true, title: '我的', redirect: 'mine' },
        component: Mine
      }
    ]
  },
  {
    path: '/classification/categoryItem',
    name: 'CategoryItem',
    component: CategoryItem,
    meta: { isAuth: false }
  },
  {
    path: '/classification/detail/:id',
    name: 'Detail',
    component: Detail,
    meta: { isAuth: false }
  },
  {
    path: '/search',
    name: 'Search',
    component: Search
  },
  {
    path: '/login',
    name: 'Login',
    meta: { isAuth: false, title: '登录' },
    component: Login,
    children: [
      {
        path: 'register',
        name: 'Register',
        meta: { isAuth: false, title: '注册', coverParent: true },
        component: Register
      },
      {
        path: 'register/:mobile',
        name: 'GetPhoneCode',
        meta: { isAuth: false, title: '注册', coverParent: true },
        component: GetPhoneCode
      }
    ]
  }
]

const router = new VueRouter({
  routes
})
// 全局路由守卫，鉴权需要验证的路由
router.beforeEach((to, from, next) => {
  if (to.meta.isAuth) {
    if (localStorage.getItem('token')) {
      next()
    } else {
      // console.log()
      // if (router.history.current.name === 'Login') {
      //   next()
      // }
      // next({ name: 'Login' })
      router.replace({ name: 'Login' })
    }
  } else {
    next()
  }
})

export default router
